package com.example.tsproject.service.impl;

import com.example.tsproject.mapper.AnalysisStudentsMapper;
import com.example.tsproject.service.AnalysisStudentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class AnalysisStudentsImpl implements AnalysisStudentsService {

    @Autowired
    private AnalysisStudentsMapper analysisStudentsMapper;

    public List<Map<String, Object>> AnalysisStudents(Integer assignmentId) {
        List<Map<String, Object>> answers = analysisStudentsMapper.findByAssignmentId(assignmentId);
        Map<String, Integer> chapterCorrectCount = new HashMap<>(); // 章节正确题数
        Map<String, Integer> chapterTotalCount = new HashMap<>();   // 章节总题数

        for (Map<String, Object> answer : answers) {
            String chapter = (String) answer.get("chapter");
            String trueOrfalse = (String) answer.get("trueOrfalse");

            chapterTotalCount.put(chapter, chapterTotalCount.getOrDefault(chapter, 0) + 1);
            if ("T".equals(trueOrfalse)) {
                chapterCorrectCount.put(chapter, chapterCorrectCount.getOrDefault(chapter, 0) + 1);
            }
        }

        List<Map<String, Object>> result = new ArrayList<>();
        for (String chapter : chapterTotalCount.keySet()) {
            int total = chapterTotalCount.get(chapter);
            int correct = chapterCorrectCount.getOrDefault(chapter, 0);
            double accuracy = (double) correct / total * 100;

            Map<String, Object> item = new HashMap<>();
            item.put("chapter", chapter);
            item.put("accuracy", accuracy);
            result.add(item);
        }

        return result;
    }
}
